package com.veetao.api.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.veetao.api.consts.HttpConstants;
import com.veetao.api.consts.McpConstants;
import com.veetao.api.model.ApiCommand;
import com.veetao.api.model.ApiResult;
import com.veetao.api.model.ApiResultCode;
import com.veetao.api.service.CommandLookupService;
import com.veetao.api.utils.McpUtils;
import com.veetao.api.utils.RequestUtils;

@Component
public class MethodNameChecker extends ApiRequestChecker {
	
	@Autowired
	private CommandLookupService commandLookupService;

	public MethodNameChecker() {
		super();
		this.setOrder(0);
	}

	@Override
	public ApiResult check(HttpServletRequest request) {
			// 解析uri到method名字，优先判断
		String methodName = McpUtils.getCmdMethodFromURI(request.getRequestURI());
		if (methodName == null) {// URL中没有时，从参数中取一次容错。
			methodName = RequestUtils.get(request,HttpConstants.PARAM_METHOD);
		}
		if (StringUtils.isEmpty(methodName)) { // 没有方法名
			return new ApiResult(ApiResultCode.E_SYS_UNKNOWN_METHOD);
		}
		request.setAttribute(McpConstants.REQ_API_METHOD_NAME, methodName);
//		final String queryString = McpUtils.buildQueryString(requestParamMap);
		final String version = RequestUtils.get(request, McpConstants.PARAM_V);
		final ApiCommand apiCommand = commandLookupService.lookupApiCommand(methodName, version);
		if (apiCommand == null) {
			// apiCommand is unknown
			return new ApiResult(ApiResultCode.E_SYS_UNKNOWN_METHOD);
		}
		
		return SUCC_RESULT;
		
	}

}
